import elasticsearch
import os
import pathlib
import sys

project_path = pathlib.Path(os.path.abspath(__file__)).parent.parent.parent
sys.path.append(str(project_path))
from etc.question_answer_config import value_index_name, attr_index_name
from utility.import_log import flog

log = flog(__file__)


class QAParser(object):
    @staticmethod
    def es_parser(es: elasticsearch.Elasticsearch, question: str, topn: int, threshold: int) -> tuple:
        '''
        first attr and first attr value
        '''
        assert isinstance(es, elasticsearch.Elasticsearch), "es should be Elasticsearch object"

        search_object = {'query': {'match': {'value': question}}, 'size': topn}
        log.info(f'开始左节点查询:{search_object}')
        results = es.search(index=value_index_name, body=search_object)
        log.info(f'共查询到 {len(results)} 条记录')
        value_list = []
        hits = results['hits']['hits']
        if hits:
            first_score = None
            for index, each in enumerate(hits):
                score = each['_score']
                temp_dict = each['_source']
                temp_dict.update({'score': score})

                if score < threshold:
                    continue

                if index == 0:
                    first_score = score
                    value_list.append(temp_dict)
                else:
                    if score == first_score:
                        value_list.append(temp_dict)
        if len(value_list):
            new_question = question.replace(value_list[0]['value'], '')
            if len(new_question)==len(question):
                log.info(f'输入不正确！')
                return [], []
            search_object = {'query': {'match': {'value': new_question}}, 'size': topn}
            log.info(f'开始右节点查询:{search_object}')
        else:
            log.info(f'查询无结果！')
            return [], []
        results = es.search(index=attr_index_name, body=search_object)
        log.info(f'共查询到 {len(results)} 条记录')
        attr_list = []
        hits = results['hits']['hits']
        if hits:
            for each in hits:
                score = each['_score']
                temp_dict = each['_source']
                temp_dict.update({'score': score})

                if score < threshold:
                    continue

                attr_list.append(temp_dict)

        log.info(f'查询结果处理完毕!')
        log.info(f'value_list: {value_list}')
        log.info(f'attr_list: {attr_list}')
        return value_list, attr_list
